package com.sky.service.user.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDTO;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.pojo.AddressBook;
import com.sky.service.user.AddressBookService;
import com.sky.vo.AddressBookVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    private final AddressBookMapper addressBookMapper;

    /**
     * 新增|修改地址
     *
     * @param dto
     */
    @Override
    public void save(AddressBookDTO dto) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        Optional<Long> id = Optional.ofNullable(addressBook.getId());
        if (id.isEmpty()) {
            //没有id,新增地址
            addressBook.setIsDefault(StatusConstant.DISABLE);
            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookMapper.addAddr(addressBook);
        }else {
            //有id修改地址
            addressBookMapper.update(addressBook);
        }
    }

    /**
     * 查询用户所有地址
     *
     * @return
     */
    @Override
    public List<AddressBookVO> queryList() {
        return addressBookMapper.queryList(BaseContext.getCurrentId());
    }

    /**
     * 查询默认地址
     */
    @Override
    public AddressBookVO queryDefAddr() {
        return addressBookMapper.queryDefAddr(BaseContext.getCurrentId());
    }

    /**
     * 删除地址
     * @param id
     */
    @Override
    public void delById(Long id) {
        addressBookMapper.delById(id);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBookVO queryById(Long id) {
        return addressBookMapper.queryById(id);
    }

    /**
     * 设置默认地址
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setDefAddr(AddressBookDTO dto) {
        //将当前用户的所有地址设置为非默认
        addressBookMapper.setAllAddrUndefult(BaseContext.getCurrentId());
        //设置当前id为默认地址
        addressBookMapper.setDefAddr(dto.getId());
    }
}
